#include "DbConnectManager.h"
#include <QFile>
#include <QDebug>
#include <QThread>
#include "CTableSession.h"
#include "CTableConfig.h"
#include "CTableQuick.h"
#include "CTableTrigger.h"

DbConnectManager::DbConnectManager(QObject *parent) : QObject(parent)
{

}

DbConnectManager::~DbConnectManager()
{
    foreach(QString strKey,m_mapDataBase.keys()){
        QSqlDatabase *pDatabase = m_mapDataBase[strKey];
        if(pDatabase){
            pDatabase->close();
            delete pDatabase;
            pDatabase = nullptr;
        }
        QSqlDatabase::removeDatabase(strKey);
    }
}

DbConnectManager *DbConnectManager::getInstance()
{
    static DbConnectManager* m_pInstance = nullptr;
    if(m_pInstance == nullptr){
        if(m_pInstance == nullptr){
            m_pInstance = new DbConnectManager();
        }
    }
    return m_pInstance;
}

bool DbConnectManager::init(QString strDbFilename)
{
//    if(!QFile::exists(strDbFilename)){
//        qWarning("数据库文件不存在:%s",strDbFilename.toUtf8().data());
//        return false;
//    }



    m_strDbFilename = strDbFilename;

    qDebug()<<"数据库驱动:"<<QSqlDatabase::drivers()<<"tables:"<<getDbConnection()->tables();

    //初始化表
    CTableSession::instance();
    CTableConfig::instance();

    CTableQuick::instance();
    CTableTrigger::instance();

    setSynMode(SynMode::Normal);

    return true;
}

bool DbConnectManager::setSynMode(SynMode mode)
{
//    PRAGMA synchronous = FULL; (2)
//    PRAGMA synchronous = NORMAL; (1)
//    PRAGMA synchronous = OFF; (0)

    //@TODO 测试未发现明显变化
    QString strSql;
    switch (mode) {
    case SynMode::Full:
        strSql = "PRAGMA synchronous = FULL;";
        break;
    case SynMode::Normal:
        strSql = "PRAGMA synchronous = NORMAL;";
        break;
    case SynMode::Off:
        strSql = "PRAGMA synchronous = OFF;";
        break;
    default:
        strSql = "PRAGMA synchronous = FULL;";
        break;
    }
    QSqlQuery query(*getDbConnection());
    bool bOk = query.exec(strSql);
    qDebug()<<"同步："<<bOk<<strSql;
    return bOk;
}

QSqlDatabase *DbConnectManager::getDbConnection()
{
    QString strDbConnectName = QString::number((quintptr)QThread::currentThread());
    QSqlDatabase *pDatabase = nullptr;
    if(!m_mapDataBase.contains(strDbConnectName)){
        pDatabase = new QSqlDatabase();
        *pDatabase = QSqlDatabase::addDatabase("QSQLITE",strDbConnectName);
        pDatabase->setDatabaseName(m_strDbFilename);
        m_mapDataBase.insert(strDbConnectName,pDatabase);
        qInfo()<<"DataBase connect count:"<<m_mapDataBase.count();
    }else{
        pDatabase = m_mapDataBase.value(strDbConnectName);
    }

    if(!pDatabase->isOpen()){
        if(pDatabase->open()){
            qInfo()<<"数据库连接打开成功! 连接名:"<<strDbConnectName;
        }else{
            qWarning()<<"数据库连接打开失败! 连接名:"<<strDbConnectName<<"当前所有连接："<<m_mapDataBase;
        }
    }

    return pDatabase;
}

